import React from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Spin, Button, Divider, Modal, Table, Input, Col, Row, Alert, message } from 'antd';
import moment from 'moment';
import router from 'umi/router';
import queryString from 'query-string';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import DescriptionList from '@/components/DescriptionList';
import FooterToolbar from '@/components/FooterToolbar';
import TextOverFlow from '../../components/TextOverFlow';
import AddDetailUpdateInv from './AddDetailUpdateInv';
import Authorized from '@/utils/Authorized';
import styles from '@/utils/utils.less';

const { Description } = DescriptionList;
const FormItem = Form.Item;
const { TextArea } = Input;
@connect(({ invoice, loading, login: { systemList } }) => ({
  invoice,
  loading: loading.models.invoice,
  systemList,
  invRecordDetail: invoice.invRecordDetail, // 发票申请记录详情数据
  invInfoList: invoice.invInfoList, // 发票信息数据
  billListData: invoice.pageData, // 账单/一次性费用明细数据
  invCompany: invoice.invCompany, // 换票回显数据
}))
@Form.create()
class ClientInfoDetails extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      typePage: null, // 区分是查看，还是取消申请
      modalVisible: false, // 账单/一次性费用弹框
      changeInvModal: false, // 换票弹框
      sysCode: 1,
      invApplyId: null, // 发票申请记录id
      invCompanyId: null, // 发票抬头id
      invRuleId: null, // 发票规则id
      visible: false,
      detailParams: {}, // 弹框参数
      detail: null,
    };
  }

  componentDidMount() {
    const { location, systemList } = this.props;
    const { type } = queryString.parse(location.search);
    const { sysCode } = systemList.filter(item => item.isSelected)[0];
    const { invApplyId } = queryString.parse(location.search);
    this.setState({ typePage: type, sysCode, invApplyId });
    // 获取发票记录详情数据
    this.fetchInvRecordDetail(invApplyId);
  }

  // 获取发票记录详情数据
  fetchInvRecordDetail = invApplyId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'invoice/getInvRecordDetail',
      payload: {
        invApplyId,
      },
    });
  };

  // 点击账单/一次性费用明细弹框
  billChargeModal = () => {
    this.setState({ modalVisible: true });
    const { dispatch } = this.props;
    const { invApplyId } = this.state;
    const pagerArg = { currentPage: 1, pageSize: 10 };
    dispatch({
      type: 'invoice/getInvApplyDataBillOnceFee',
      payload: {
        pagerArg,
        invApplyId,
      },
    });
  };

  // 关闭账单/一次性费用明细及换票弹框
  handleClose = () => {
    this.setState({ modalVisible: false, changeInvModal: false });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    const { invApplyId } = this.state;
    const { dispatch } = this.props;
    const pagerArg = { currentPage: pagination.current, pageSize: pagination.pageSize };
    dispatch({
      type: 'invoice/getInvApplyDataBillOnceFee',
      payload: {
        pagerArg,
        invApplyId,
      },
    });
  };

  // 点击换票
  openExchangeInv = (invCompanyId, invRuleId) => {
    this.setState({ changeInvModal: true, invCompanyId, invRuleId });
    const { dispatch } = this.props;
    dispatch({
      type: 'invoice/getInvApplyCompany',
      payload: {
        invCompany: { invCompanyId },
      },
    });
  };

  // 换票提交数据
  exchangeInvSubmit = () => {
    const { dispatch, form } = this.props;
    const { invCompanyId, invApplyId, invRuleId } = this.state;
    form.validateFieldsAndScroll((err, values) => {
      const temp = values;
      if (err) return;
      temp.invCompanyId = invCompanyId;
      const params = {
        invCompany: values,
        invRule: {
          invRuleId,
        },
      };
      dispatch({
        type: 'invoice/exchangeInvSubmit',
        payload: params,
      }).then(response => {
        if (response.success) {
          message.success('提交成功');
          this.setState({ changeInvModal: false });
          // 获取发票记录详情数据
          this.fetchInvRecordDetail(invApplyId);
        } else {
          message.warning(response.message || '换票提交数据失败：服务器端错误！');
        }
      });
    });
  };

  // 取消申请提交数据
  cancelResonSubmit = () => {
    const { dispatch, form } = this.props;
    const { invApplyId } = this.state;
    form.validateFields(['remerk'], (err, fieldsValue) => {
      if (err) return;
      dispatch({
        type: 'invoice/cancelReasonSubmit',
        payload: {
          remerk: fieldsValue.remerk,
          invApplyId,
        },
      }).then(response => {
        if (response.success) {
          message.success(`提交成功！`);
          router.push('/fmmanage/invoice/index?activeKey=1');
        } else {
          message.warning(response.message || '取消原因提交数据失败：服务器端错误！');
        }
      });
    });
  };

  onRef = ref => {
    this.child = ref;
  };

  // 获取发票信息详情数据
  getDetail = record => {
    const detailParams = { invCompany: { invCompanyId: record.invCompanyId } };
    this.setState({ visible: true, detailParams, detail: 1 }, () => {
      this.child.getDetail();
    });
  };

  // 模态框显隐
  handleModalVisible = (_, flag) => {
    this.setState({
      visible: !!flag,
    });
  };

  render() {
    const {
      loading,
      form: { getFieldDecorator },
      invRecordDetail,
      invInfoList,
      billListData,
      invCompany,
    } = this.props;
    const {
      modalVisible,
      typePage,
      changeInvModal,
      sysCode,
      visible,
      detailParams,
      detail,
    } = this.state;
    // 取消原因表单布局
    const formItemLayoutModal = {
      labelCol: { md: { span: 2 } },
      wrapperCol: { md: { span: 20, offset: 1 } },
    };
    // 换票表单布局
    const formItemLayout = {
      labelCol: { md: { span: 9 } },
      wrapperCol: { md: { span: 15 } },
    };
    // 换票原因布局
    const formItemReson = {
      labelCol: { md: { span: 3 } },
      wrapperCol: { md: { span: 21 } },
    };

    // 账单
    const billColumns = [
      {
        title: sysCode === 1 ? '客户名称' : null,
        dataIndex: sysCode === 1 ? 'custName' : null,
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: sysCode !== 1 ? '账单编号' : null,
        dataIndex: sysCode !== 1 ? 'key' : null,
        align: 'center',
        render: (text, record, index) => <span>{sysCode !== 1 ? index + 1 : null}</span>,
      },
      {
        title: sysCode === 1 ? '商务合同' : '签约方',
        dataIndex: sysCode === 1 ? 'contName' : 'custName',
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: sysCode === 1 ? '成本中心' : null,
        dataIndex: sysCode === 1 ? 'costCenterName' : null,
        render: text => text || '--',
      },
      {
        title: '账单年月',
        dataIndex: 'billYm',
        render: text => (
          <span>
            {(text && `${text.toString().substr(0, 4)}-${text.toString().substr(4, 5)}`) || '--'}
          </span>
        ),
      },
      {
        title: '账单金额（元）',
        dataIndex: 'billAmo',
        align: 'right',
        render: text => (text === 0 ? 0 : (text && text) || '--'),
      },
    ];
    // 一次性费用明细
    const onceChargeColumns = [
      {
        title: sysCode === 1 ? '客户名称' : '签约方',
        dataIndex: 'custName',
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: sysCode === 1 ? '商务合同' : null,
        dataIndex: sysCode === 1 ? 'custContName' : null,
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '产品',
        dataIndex: 'pdName',
        render: text => text || '--',
      },
      {
        title: '业务年月',
        dataIndex: 'feeYm',
        render: text => (
          <span>
            {(text && `${text.toString().substr(0, 4)}-${text.toString().substr(4, 5)}`) || '--'}
          </span>
        ),
      },
      {
        title: '收费总金额（元）',
        dataIndex: 'feeAmo',
        align: 'right',
        render: text => (text === 0 ? 0 : (text && text) || '--'),
      },
    ];
    // 发票信息数据
    const invInfoColumns = [
      {
        title: '序号',
        dataIndex: 'key',
        align: 'center',
        render: (text, record, index) => (
          <p
            style={{
              padding: '0 16px',
              margin: '20px 0',
            }}
          >
            {index + 1 || '--'}
          </p>
        ),
      },
      {
        title: '成本中心',
        dataIndex: 'costIdName',
        render: text => (
          <p
            style={{
              padding: '0 16px',
              margin: '20px 0',
            }}
          >
            {text || '--'}
          </p>
        ),
      },
      {
        title: '发票类型',
        dataIndex: 'invTypeName',
        align: 'center',
        render: text => (
          <p
            style={{
              padding: '0 16px',
              margin: '20px 0',
            }}
          >
            {text || '--'}
          </p>
        ),
      },
      {
        title: '发票抬头',
        dataIndex: 'holderName',
        render: text => (
          <p
            style={{
              padding: '0 16px',
              margin: '20px 0',
            }}
          >
            {text || '--'}
          </p>
        ),
      },
      {
        title: '开票项目',
        dataIndex: 'project',
        align: 'center',
        render: (text, record) => {
          if (record.invTerm && record.invTerm.length) {
            return (
              <div>
                {record.invTerm.map((item, index) => (
                  <div>
                    {index === 0 ? null : (
                      <Divider solid="true" style={{ margin: 0, padding: 0 }} />
                    )}
                    <p
                      style={{
                        margin: index === 0 ? '20px 0 20px 0' : '15px 0 20px 0',
                        padding: '0 16px',
                      }}
                    >
                      {item.invTermName || '--'}
                    </p>
                  </div>
                ))}
              </div>
            );
          }
          return (
            <p
              style={{
                padding: '0 16px',
                margin: '20px 0',
              }}
            >
              --
            </p>
          );
        },
      },
      {
        title: '金额',
        dataIndex: 'invAmount',
        align: 'center',
        render: (text, record) => {
          if (record.invTerm && record.invTerm.length) {
            return (
              <div>
                {record.invTerm.map((item, index) => (
                  <div>
                    {index === 0 ? null : (
                      <Divider solid="true" style={{ margin: 0, padding: 0 }} />
                    )}
                    <p
                      style={{
                        margin: index === 0 ? '20px 0 20px 0' : '15px 0 20px 0',
                        padding: '0 16px',
                      }}
                    >
                      {item.invAmount || '--'}
                    </p>
                  </div>
                ))}
              </div>
            );
          }
          return (
            <p
              style={{
                padding: '0 16px',
                margin: '20px 0',
              }}
            >
              --
            </p>
          );
        },
      },
      {
        title: '交付方式',
        dataIndex: 'invPayName',
        align: 'center',
        render: text => (
          <p
            style={{
              padding: '0 16px',
              margin: '20px 0',
            }}
          >
            {text || '--'}
          </p>
        ),
      },
      {
        title: '发票状态',
        dataIndex: 'invStateName',
        align: 'center',
        render: text => (
          <p
            style={{
              padding: '0 16px',
              margin: '20px 0',
            }}
          >
            {text || '--'}
          </p>
        ),
      },
      {
        title: '操作',
        dataIndex: 'operName',
        align: 'center',
        render: (text, record) => (
          <span>
            <a onClick={() => this.getDetail(record)}>查看</a>
            {/* {发票状态是 --已领取} */}
            <Authorized authority="business:invoice:replaceInvoice" noMatch={null}>
              {record.invState && record.invState === 3 && <Divider type="vertical" />}
            </Authorized>
            <Authorized authority="business:invoice:replaceInvoice" noMatch={null}>
              {record.invState && record.invState === 3 && (
                <a onClick={() => this.openExchangeInv(record.invCompanyId, record.invRuleId)}>
                  换票
                </a>
              )}
            </Authorized>
          </span>
        ),
      },
    ];

    return (
      <PageHeaderWrapper>
        <Spin spinning={loading}>
          <Card
            title={<span style={{ fontWeight: 'bolder' }}>申请信息</span>}
            extra={
              <a href="#" onClick={() => this.billChargeModal()}>
                {invRecordDetail.feeType && invRecordDetail.feeType === 1
                  ? '账单明细'
                  : '一次性费用明细'}
              </a>
            }
          >
            <DescriptionList>
              {sysCode === 1 ? (
                <Description term="客户/供应商名称">
                  {invRecordDetail.custSuppName ? invRecordDetail.custSuppName : '--'}
                </Description>
              ) : (
                <Description term="签约方">
                  {invRecordDetail.custSuppName ? invRecordDetail.custSuppName : '--'}
                </Description>
              )}
              {sysCode === 1 ? (
                <Description term="合同名称">
                  {invRecordDetail.contName ? invRecordDetail.contName : '--'}
                </Description>
              ) : null}
              <Description term="服务类型">
                {invRecordDetail.invRule && invRecordDetail.invRule.serTypeName
                  ? invRecordDetail.invRule.serTypeName
                  : '--'}
              </Description>
              <Description term="是否全额计税">
                {invRecordDetail.invRule && invRecordDetail.invRule.fullyFlagName
                  ? invRecordDetail.invRule.fullyFlagName
                  : '--'}
              </Description>
            </DescriptionList>
            <Divider dashed />
            <DescriptionList>
              <Description term="服务费（元）">
                {invRecordDetail.invBill && invRecordDetail.invBill.costAmount === 0
                  ? 0
                  : (invRecordDetail.invBill && invRecordDetail.invBill.costAmount) || '--'}
              </Description>
              <Description term="代收社保（元）">
                {invRecordDetail.invBill && invRecordDetail.invBill.insAmount === 0
                  ? 0
                  : (invRecordDetail.invBill && invRecordDetail.invBill.insAmount) || '--'}
              </Description>
              <Description term="代收公积金（元）">
                {invRecordDetail.invBill && invRecordDetail.invBill.accuAmount === 0
                  ? 0
                  : (invRecordDetail.invBill && invRecordDetail.invBill.accuAmount) || '--'}
              </Description>
              <Description term="代发工资（元）">
                {invRecordDetail.invBill && invRecordDetail.invBill.wagesAmount === 0
                  ? 0
                  : (invRecordDetail.invBill && invRecordDetail.invBill.wagesAmount) || '--'}
              </Description>
              <Description term="代收档案费（元）">
                {invRecordDetail.invBill && invRecordDetail.invBill.archvAmount === 0
                  ? 0
                  : (invRecordDetail.invBill && invRecordDetail.invBill.archvAmount) || '--'}
              </Description>
              <Description term="代报税金额（元）">
                {invRecordDetail.invBill && invRecordDetail.invBill.taxAmount === 0
                  ? 0
                  : (invRecordDetail.invBill && invRecordDetail.invBill.taxAmount) || '--'}
              </Description>
              <Description term="代收代付合计（元）">
                {invRecordDetail.invBill && invRecordDetail.invBill.agtsrvSum === 0
                  ? 0
                  : (invRecordDetail.invBill && invRecordDetail.invBill.agtsrvSum) || '--'}
              </Description>
              <Description term="合计金额（元）">
                {invRecordDetail.invBill && invRecordDetail.invBill.sumAmount === 0
                  ? 0
                  : (invRecordDetail.invBill && invRecordDetail.invBill.sumAmount) || '--'}
              </Description>
            </DescriptionList>
            <Divider dashed />
            <DescriptionList>
              <Description term="申请人">
                {invRecordDetail.creName ? invRecordDetail.creName : '--'}
              </Description>
              <Description term="申请时间">
                {invRecordDetail.creTime
                  ? moment(invRecordDetail.creTime).format('YYYY-MM-DD HH:mm')
                  : '--'}
              </Description>
              {/* {发票状态是 --已取消 */}
              {invRecordDetail.invState && invRecordDetail.invState === 7 ? (
                <Description term="取消人员">
                  {invRecordDetail.invApplyOpt && invRecordDetail.invApplyOpt.operName
                    ? invRecordDetail.invApplyOpt.operName
                    : '--'}
                </Description>
              ) : null}
              {invRecordDetail.invState && invRecordDetail.invState === 7 ? (
                <Description term="取消时间">
                  {invRecordDetail.invApplyOpt && invRecordDetail.invApplyOpt.operTime
                    ? moment(invRecordDetail.invApplyOpt.operTime).format('YYYY-MM-DD HH:mm')
                    : '--'}
                </Description>
              ) : null}
              {invRecordDetail.invState && invRecordDetail.invState === 7 ? (
                <Description term="取消原因">
                  {invRecordDetail.invApplyOpt && invRecordDetail.invApplyOpt.operRsn
                    ? invRecordDetail.invApplyOpt.operRsn
                    : '--'}
                </Description>
              ) : null}
            </DescriptionList>
          </Card>
          <Card title={<span style={{ fontWeight: 'bolder' }}>发票信息</span>}>
            <Alert
              message={
                <div>
                  合计开票金额（元）：
                  <span style={{ color: '#088FEA' }}>
                    {invInfoList.sumAmount === 0 ? 0 : invInfoList.sumAmount}
                  </span>
                  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 未开票金额：
                  <span style={{ color: '#088FEA' }}>
                    {invInfoList.noSumAmount === 0 ? 0 : invInfoList.noSumAmount}
                  </span>
                </div>
              }
              type="info"
              showIcon
            />
            <Table
              dataSource={invInfoList.responseInvApplyListDto || []}
              columns={invInfoColumns}
              rowKey={record => record.invCompanyId}
              loading={loading}
              pagination={false}
              bordered
              className={styles.invRowPadding}
            />
          </Card>
          {typePage === '2' ? (
            <Card title={<span style={{ fontWeight: 'bolder' }}>取消</span>}>
              <Form layout="horizontal">
                <FormItem {...formItemLayoutModal} label="取消原因">
                  {getFieldDecorator('remerk', {
                    rules: [{ required: true, message: '请输入' }],
                  })(<TextArea rows={4} placeholder="请输入取消原因" maxLength={100} />)}
                </FormItem>
              </Form>
            </Card>
          ) : null}
          <FooterToolbar style={{ width: '100%' }}>
            <Button onClick={() => router.goBack()}>返回</Button>
            {typePage === '2' ? (
              <Button
                type="primary"
                style={{ marginLeft: 20 }}
                onClick={() => this.cancelResonSubmit()}
              >
                提交
              </Button>
            ) : null}
          </FooterToolbar>
          {/* {账单/一次性费用弹框} */}
          <Modal
            width={1000}
            visible={modalVisible}
            onCancel={() => this.handleClose()}
            title={
              invRecordDetail.feeType && invRecordDetail.feeType === 1
                ? '账单明细'
                : '一次性费用明细'
            }
            footer={[
              <Button
                key="submit"
                type="primary"
                loading={loading}
                onClick={() => this.handleClose()}
              >
                关闭
              </Button>,
            ]}
            destroyOnClose
          >
            <StandardTable
              selectedRows={[]}
              selectedRowKeys={[]}
              rowSelection={null}
              loading={loading}
              data={billListData}
              rowKey="custId"
              columns={
                invRecordDetail.feeType && invRecordDetail.feeType === 1
                  ? billColumns
                  : onceChargeColumns
              }
              onChange={this.handleStandardTableChange}
            />
          </Modal>
          {/* {换票弹框} */}
          <Modal
            width={800}
            visible={changeInvModal}
            onCancel={() => this.handleClose()}
            title="换票申请"
            footer={[
              <Button onClick={() => this.handleClose()}>取消</Button>,
              <Button
                key="submit"
                type="primary"
                loading={loading}
                onClick={() => this.exchangeInvSubmit()}
              >
                提交
              </Button>,
            ]}
            destroyOnClose
          >
            <Form layout="horizontal">
              <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={12} sm={24} pull={2}>
                  <FormItem {...formItemLayout} label="单位名称">
                    {getFieldDecorator('holderName', {
                      rules: [{ required: true, message: '请输入' }],
                      initialValue: invCompany.holderName || undefined,
                    })(<Input placeholder="请输入" />)}
                  </FormItem>
                </Col>
                <Col md={12} sm={24}>
                  <FormItem {...formItemLayout} label="纳税人识别号">
                    {getFieldDecorator('taxerIdNo', {
                      rules: [{ required: true, message: '请输入' }],
                      initialValue: invCompany.taxerIdNo || undefined,
                    })(<Input placeholder="请输入" />)}
                  </FormItem>
                </Col>
              </Row>
              <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={12} sm={24} pull={2}>
                  <FormItem {...formItemLayout} label="注册地址">
                    {getFieldDecorator('holderAddrs', {
                      rules: [{ required: true, message: '请输入' }],
                      initialValue: invCompany.holderAddrs || undefined,
                    })(<Input placeholder="请输入" />)}
                  </FormItem>
                </Col>
                <Col md={12} sm={24}>
                  <FormItem {...formItemLayout} label="注册电话">
                    {getFieldDecorator('phone', {
                      rules: [{ required: true, message: '请输入' }],
                      initialValue: invCompany.phone || undefined,
                    })(<Input placeholder="请输入" />)}
                  </FormItem>
                </Col>
              </Row>
              <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={12} sm={24} pull={2}>
                  <FormItem {...formItemLayout} label="开户行">
                    {getFieldDecorator('bankOfDepoName', {
                      rules: [{ required: true, message: '请输入' }],
                      initialValue: invCompany.bankOfDepoName || undefined,
                    })(<Input placeholder="请输入" />)}
                  </FormItem>
                </Col>
                <Col md={12} sm={24}>
                  <FormItem {...formItemLayout} label="银行账户">
                    {getFieldDecorator('bankAcco', {
                      rules: [{ required: true, message: '请输入' }],
                      initialValue: invCompany.bankAcco || undefined,
                    })(<Input placeholder="请输入" />)}
                  </FormItem>
                </Col>
              </Row>
              <Row gutter={{ md: 8, lg: 24, xl: 48 }} style={{ marginLeft: '-25px' }}>
                <Col md={24} sm={24}>
                  <FormItem {...formItemReson} label="换票原因">
                    {getFieldDecorator('remark', {
                      rules: [{ required: true, message: '请输入' }],
                    })(<TextArea rows={2} placeholder="请输入换票原因" maxLength={100} />)}
                  </FormItem>
                </Col>
              </Row>
            </Form>
          </Modal>
          {/* {发票信息详情弹框} */}
          <AddDetailUpdateInv
            maskClosable={false} // 点击其他地方允不允许关闭
            visible={visible} // 控制显示隐藏
            handleModalVisible={this.handleModalVisible}
            addOrDetail={4} // 是新增还是修改还是详情（1新增，2修改，3自己详情，4小兰详情）
            detailUpdate={2} // 详情里有没有修改按钮（1有，2没有）
            style={{ width: 1200 }}
            detail={detail} // 详情和修改传 1 ，新增和详情转修改传 2
            detailParams={detailParams} // 传过去的详情id
            onRef={this.onRef}
          />
        </Spin>
      </PageHeaderWrapper>
    );
  }
}
export default ClientInfoDetails;
